// 一个安全的api  通过 时间有效性 + 密码 + 公钥私钥加密 
var express = require('express');
var path = require('path');
var fs = require('fs');
const crypto = require('crypto');
let ejs = require('ejs');

var app = express();

var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

const data = "3023704769";

var publicKey = '';
var privateKey = '';

// 公钥和私钥文件 通过脚本会隔一段时间重新生成
// 根据 公钥 私钥文件 生成 html模板 
function genKey(){
    publicKey = fs.readFileSync('./rsa_public_key.pem').toString('ascii');
    privateKey = fs.readFileSync('./rsa_private_key.pem').toString('ascii');

    const encodeData = crypto.publicEncrypt(publicKey, Buffer.from(data)).toString('base64');
    console.log("encoded:"+ encodeData);

    const decodeData = crypto.privateDecrypt(privateKey, Buffer.from(encodeData.toString('base64'), 'base64'));
    console.log("decode: ", decodeData.toString());
    
    var indexHtml ='';
    ejs.renderFile(path.join(__dirname,'index.html'),{signal:encodeData},function(err,result){
        indexHtml = result;
    });
    return indexHtml;
}

// 将router对象 与 app 关联起来
app.get('/',function(req,res){
    res.send(genKey());
});

app.get('/index',function(req,res){
    res.send(genKey());
});

app.post('/404',function(req,res){
    var time = new Date();
    if (time.getTime() + 2000 >= req.body.time && req.body.pub === '123' && crypto.privateDecrypt(privateKey, Buffer.from(req.body.signal.toString('base64'), 'base64')).toString() === "3023704769") {
        // var data = crypto.privateDecrypt(privateKey, Buffer.from(req.body.signal.toString('base64'), 'base64')).toString();
        // console.log("decode: ", decodeData.toString());
        res.sendFile(path.join(__dirname,'response.html'),function(err){
            if (err) {
                throw err;
            }
        });
    }else{
        res.send("公钥错误 滚");
    } 
});

// 启动服务
app.listen(8000, function () {
    console.log("http://localhost:8000");
})